import createElement from './createElement';
import updateChildren from './updateChildren';

export default function patchVnode(oldVnode, newVnode) {
  // 判断是不是同一个对象
  if (oldVnode === newVnode) return;
  // 判断newVnode是否有text
  if (newVnode.text != undefined && (!newVnode.children || !newVnode.children.length)) {
    if (oldVnode.text != newVnode.text) {
      oldVnode.elm.innerHTML = newVnode.text;
    }
  } else {
    // newVnode没有text，有children的情况
    if (oldVnode.children && oldVnode.children.length) {
      // 最难
      // oldVnode有children
      updateChildren(oldVnode.elm, oldVnode.children, newVnode.children);
    } else {
      // oldVnode没有children
      // 移除oldVnode中的text
      if (oldVnode.elm && oldVnode.elm.innerHTML) {
        oldVnode.elm.innerHTML = '';
      }
      // 新增子节点
      if (!newVnode.children || !newVnode.children.length) return;
      for (let i = 0; i < newVnode.children.length; i++) {
        let ch = newVnode.children[i];
        let chDom = createElement(ch);
        oldVnode.elm.appendChild(chDom);
      }
    }
  }
}